<!--
* @FileDescription:
-->
<template>
  <div class="PipCheck">
    <div class="ag-toolbar">
      <button
        id="undoBtn"
        class="ag-btn"
        v-on:click="undo()"
        :disabled="agbtndis.undo"
      >
        <el-icon><DArrowLeft /></el-icon>撤销
      </button>
      <button
        id="redoBtn"
        class="ag-btn"
        v-on:click="redo()"
        :disabled="agbtndis.redo"
      >
        <el-icon><DArrowRight /></el-icon>恢复
      </button>
      <button
        id="addrowBtn"
        class="ag-btn"
        v-on:click="addrow()"
        :disabled="agbtndis.addrow"
      >
        <el-icon><Plus /></el-icon>添加行
      </button>
      <button
        id="delrowBtn"
        class="ag-btn"
        v-on:click="delrow()"
        :disabled="agbtndis.delrow"
      >
        <el-icon><Minus /></el-icon>删除行
      </button>
      <button
        id="impoBtn"
        class="ag-btn"
        v-on:click="openImpo()"
        :disabled="agbtndis.import"
      >
        <el-icon><Upload /></el-icon>导入数据
      </button>
      <input
        type="file"
        ref="importElem"
        multiple
        accept="text/plain,text/csv"
        style="display: none"
        :oninput="impotab"
      />
      <button
        id="saveBtn"
        class="ag-btn"
        v-on:click="savetab()"
        :disabled="agbtndis.save"
      >
        <el-icon><UploadFilled /></el-icon>提交至数据库
      </button>
      <button
        id="expoBtn"
        class="ag-btn"
        v-on:click="expotab()"
        :disabled="agbtndis.export"
      >
        <el-icon><Download /></el-icon>下载
      </button>
    </div>
    <ag-grid-vue
      class="ag-theme-balham"
      :rowData="table_data"
      :columnDefs="query_columns"
      undoRedoCellEditing="true"
      enableCellChangeFlash="true"
      :defaultColDef="defaultColDef"
      rowSelection="multiple"
      :onCellValueChanged="onCellValueChanged"
      :onGridReady="onGridReady"
      style="width: 100%; height: 300px"
    ></ag-grid-vue>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { dbquery } from "@/apis/query";
import columnsnorm from "@/apis/columnsnorm";
import AgDatePicker from "@/components/AgDatePicker.vue";
//import queryresnorm from "@/apis/queryresnorm";
//import { AgGridVue } from "ag-grid-vue3";
import { ref } from "vue";
var gridApi = null;
var table_data = ref([]);
var raw_data = null;
var raw_id = null;
var query_columns = ref([]);
var gridColumnApi = null;
var agbtndis = ref({
  undo: true,
  redo: true,
  addrow: false,
  delrow: true,
  save: true,
});
//var querying = {};
//var query_result = null;
var defaultColDef = {
  resizable: true,
  editable: true,
  wrapText: true,
  autoHeight: true,
};
const coldefs = {
  井号: {
    filter: "agTextColumnFilter",
  },
  开发单元: {
    filter: "agTextColumnFilter",
  },
  序号: {
    hide: true,
  },
  显示标记: {
    cellEditorSelector: () => {
      return {
        component: "agSelectCellEditor",
        params: { values: ["1", "0"] },
      };
    },
  },
  上次作业时间: {
    cellEditorSelector: () => {
      return {
        component: AgDatePicker,
        params: { values: ["1", "0"] },
      };
    },
  },
  是否内衬: {
    cellEditorSelector: () => {
      return {
        component: "agSelectCellEditor",
        params: { values: ["1", "0"] },
      };
    },
  },
};
function onGridReady(params) {
  gridApi = params.api;
  gridColumnApi = params.columnApi;
  query();
  //autoSizeAll();
}

function updateAgbtndis() {
  agbtndis.value.undo = gridApi.getCurrentUndoSize() > 0 ? false : true;
  agbtndis.value.redo = gridApi.getCurrentRedoSize() > 0 ? false : true;
  agbtndis.value.save = gridApi.getCurrentUndoSize() > 0 ? false : true;
  agbtndis.value.delrow = gridApi.getDisplayedRowCount() > 0 ? false : true;
}
function undo() {
  gridApi.undoCellEditing();
}
function redo() {
  gridApi.redoCellEditing();
}
function getFormatDate(date) {
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  var d = date.getDate();
  return y + (m < 10 ? "-0" : "-") + m + (d < 10 ? "-0" : "-") + d;
}
function addrow(items = [{ 上次作业时间: getFormatDate(new Date()) }]) {
  var newItem = items;
  gridApi.applyTransaction({
    add: newItem,
  });
  updateAgbtndis();
  agbtndis.value.save = false;
}
function delrow() {
  var selectedRows = gridApi.getSelectedRows();
  gridApi.applyTransaction({ remove: selectedRows });
  updateAgbtndis();
  agbtndis.value.save = false;
}
function onCellValueChanged() {
  updateAgbtndis();
}
function getGridData() {
  const res = [];
  gridApi.forEachNode((node) => {
    res.push(JSON.parse(JSON.stringify(node.data)));
  });
  return res;
}
function autoSizeAll() {
  gridColumnApi.autoSizeAllColumns(true);
}
function getGridId() {
  const gridId = [];
  gridApi.forEachNode(function (node) {
    gridId.push(JSON.parse(JSON.stringify(node.rowIndex)));
  });
  return gridId;
}

import { readCSV, toJSON } from "danfojs";
var importElem = ref();
function openImpo() {
  importElem.value.value = "";
  importElem.value.click();
  //var importData = savetab({ tabData: importData });
}
function impotab() {
  if (importElem.value != "") {
    for (const i in importElem.value.files) {
      readCSV(importElem.value.files[i], { encoding: "GB2312" }).then((df) =>
        addrow(toJSON(df))
      );
    }
  }
}
function expotab() {
  gridApi.exportDataAsCsv({ fileName: "检管维护数据" });
}
/*
const checkSavingTable = new Promise(function (resolve, reject) {
  var tabData = getGridData();
  var wns = [];
  var blocks = [];
  var pass = null;
  dbquery("dbpytrol", "select 开发单元 from pytrol.checkinterval ")
    .then((result) => {
      if (result.data.length) {
        result.data.forEach((value) => {
          blocks.push(value["开发单元"]);
        });
      }
    })
    .then(() => {
      try {
        tabData.forEach((row) => {
          console.log(row["开发单元"]);
          if (Object.keys(row).length < 5) {
            throw 0;
          }
          //录入信息不完整
          else if (!blocks.includes(row["开发单元"])) throw -1;
          //填写正确的开发单元
          else if (wns.includes(row["井号"])) throw -2;
          //井记录重复
        });
      } catch (err) {
        pass = parseInt(err);
        resolve(pass);
      }
    });
});

function checkSavingTable() {
  var tabData = getGridData();
  var wns = [];
  try {
    tabData.forEach((row, index) => {
      if (Object.keys(row).length < 5) throw [0, index];
      //录入信息不完整
      else if (wns.includes(row["井号"])) throw [-2, index];
      //井记录重复
    });
  } catch (e) {
    return e;
  }
  return [1];
}
*/
function tabdatatosql(rowObj, database, type = "add", col = "井号") {
  console.log("rowObj", rowObj);
  if (type == "add") {
    return `replace INTO ${database} \
   (${Object.keys(rowObj).join(",")}) \
   VALUES ('${Object.values(rowObj).join("','")}') `;
  } else if (type == "delete") {
    return `delete from ${database} \
    where ${col}= '${rowObj[col]}'`;
  }
}
function savetab(
  rawId = raw_id,
  rawData = JSON.parse(JSON.stringify(table_data.value))
) {
  var sql = [];
  var sql_del = [];
  console.log(rawId, rawData);
  var wns = [];
  var tabId = [];
  try {
    gridApi.forEachNode((node) => {
      /*
      console.log(
        JSON.stringify(raw_data[node.data["序号"]]),
        JSON.stringify(node.data),
        JSON.stringify(raw_data[node.data["序号"]]) != JSON.stringify(node.data)
      );*/
      if (Object.keys(node.data).length < 5)
        //录入信息不完整
        throw [0, node.rowIndex];
      else if (wns.includes(node.data["井号"]))
        //井记录重复
        throw [-2, node.rowIndex];
      else if (
        rawId.includes(node.data["序号"]) &&
        JSON.stringify(raw_data[node.data["序号"]]) != JSON.stringify(node.data)
      ) {
        tabId.push(node.rowIndex);
        console.log("修改");
        wns.push(node.data["井号"]);
        delete node.data["序号"];
        sql.push(tabdatatosql(node.data, "pytrol.injectionpip"));
        console.log(sql);
      } else if (!rawId.includes(node.data["序号"])) {
        tabId.push(node.rowIndex);
        console.log("新增");
        wns.push(node.data["井号"]);
        delete node.data["序号"];
        sql.push(tabdatatosql(node.data, "pytrol.injectionpip"));
      } else tabId.push(node.rowIndex);
    });
    console.log(sql);
  } catch (e) {
    console.log("checkflag", e);
    ElMessageBox.alert(
      e[0] == 0
        ? "录入信息不完整"
        : e[0] == -1
        ? "填写正确的开发单元"
        : "井记录重复",
      {
        // if you want to disable its autofocus
        // autofocus: false,
        confirmButtonText: "OK",
      }
    );
    return;
  }
  rawId.forEach((value, index) => {
    if (!tabId.includes(index)) {
      sql_del.push(
        tabdatatosql(rawData[value], "pytrol.injectionpip", "delete")
      );
      console.log("sql_del_sentense", sql_del);
    }
  });
  console.log("sql_del", sql_del);
  //提交数据
  sql = sql_del.concat(sql);
  var sqlstr = sql.join(";");
  dbquery("dbpytrol", sqlstr)
    .catch((reason) => {
      ElMessage({
        duration: 0,
        showClose: true,
        type: "error",
        message: reason,
      });
    })
    .then(() => {
      query();
      ElMessage({
        type: "success",
        message: "提交成功",
      });
    });

  /*
  sql.forEach((value) => {
    dbquery("dbpytrol", value)
      .catch((reason) => {
        ElMessage({
          duration: 0,
          showClose: true,
          type: "error",
          message: reason,
        });
      })
      .then(() => {
        query();
        ElMessage({
          type: "success",
          message: "提交成功",
        });
      });

  });
  */
}

function query() {
  //querying = true;
  var sql =
    "select 井号,injectionpip.`开发单元`,if(是否内衬,1,0) as 是否内衬,DATE_FORMAT(上次作业时间,'%Y-%m-%d') as 上次作业时间,if( 显示标记,1,0) as 显示标记 from pytrol.injectionpip ";

  dbquery("dbpytrol", sql)
    .catch(async (err) => {
      ElMessage({
        message: err,
        type: "err",
      });
    })
    .then((result) => {
      if (result.data.err) {
        ElMessage({
          message: result.data.err + ":" + result.data.message,
          type: "error",
        });
      } else if (result.data.length == 0) {
        ElMessage({
          message: "数据为空",
          type: "warning",
        });
      } else {
        //query_result = JSON.parse(JSON.stringify(result.data));

        var temparray = [];
        var temprow = null;
        result.data.forEach((value, index) => {
          temprow = value;
          temprow["序号"] = index;
          temparray.push(temprow);
        });
        query_columns.value = columnsnorm(
          Object.keys(temparray[0]),
          ["field"],
          coldefs
        );
        table_data.value = temparray;
        //console.log(query_columns.value);
        //console.log(table_data.value);
        //console.log("query done");
      }
    })
    .then(() => {
      updateAgbtndis();
      raw_data = JSON.parse(JSON.stringify(table_data.value));
      raw_id = getGridId();
      //autoSizeAll();
    });
}
//query();
</script>

<style scoped>
.ag-toolbar {
  margin-bottom: 5px;
}

#expoBtn {
  display: inline;
  float: right;
}
</style>
